import { useTabsStore } from '@/store/modules/tabs'
import { handleActivePath } from '@/utils/routes'
import { findLastIndex } from 'lodash'
import { gp } from '@gp'

export default function () {
  const router = useRouter()
  const route = useRoute()
  const { delVisitedRoute } = useTabsStore()

  const getParentPath = (path: string) => {
    const i = findLastIndex(path, (o) => o == '/')
    return path.substring(0, i)
  }

  const goBack = async (backUrl?: any) => {
    const detailPath = await handleActivePath(route, true)
    if (backUrl == undefined) {
      backUrl = getParentPath(detailPath)
    }
    await router.push(backUrl)
    await delVisitedRoute(detailPath)
  }

  const goUrl = (url: string, query?: any) => {
    if (url.indexOf('/') != 0) {
      url = `${route.path}/${url}`
    }
    console.log(url)
    router.push({
      path: url,
      query: query,
    })
  }

  const refreshParent = () => {
    gp.$pub('reload-view-data', route.path)
  }

  return {
    goUrl,
    goBack,
    refreshParent,
  }
}
